import { BadRequestException, Injectable } from '@nestjs/common';
import { cmdExec, getBundle } from '../utils';
import { wifiIpCmd } from './cmd';
import { Socket } from 'net';

const getWifiIpByIfconfig = async (devId: string) => {
  let ip = '';
  let cmd_ret: string | string[];
  try {
    cmd_ret = await cmdExec(wifiIpCmd.hdc.getIpOld(devId)).then((res) => {
      return (
        res
          .split('\r\n')
          .filter(Boolean)
          .map((item) => item.trim()) || []
      );
    });
    if (cmd_ret && cmd_ret[0]) {
      const ip_info = cmd_ret[0].split(' ') || [];
      if (ip_info && ip_info[1]) {
        //addr:xx.xx.xx.xx
        const paras = ip_info[1].split(':') || [];
        if (paras && paras[1]) ip = paras[1];
      }
    }
  } catch (err) {
    console.log('getWifiIpByIfconfig err', err);
  }
  return ip;
};

const getWifiIpBySocket = (SN: string) => {
  return new Promise<string>(async (resolve, reject) => {
    try {
      let bundle = '';
      bundle = await getBundle(SN);
      await cmdExec(wifiIpCmd.hdc.getIp(SN, bundle));
      await cmdExec('hdc fport tcp:12347 tcp:4567');
      const client = new Socket();
      client.on('data', (data) => {
        resolve(data.toString());
      });
      setTimeout(() => {
        client.connect(12347, '127.0.0.1', () => {
          client.write('get_ip');
        });
      }, 500);
      client.on('error', (err) => {
        console.log(err, 'getAppListBySocket connect error');
        reject(err);
      });
    } catch (err) {
      console.log('getWifiIpBySocket err', err);
      reject(err);
    }
  });
};

@Injectable()
export class WifiIpService {
  async getWifiIP(SN: string, getWithInfo?: boolean) {
    try {
      let ip = '';
      ip = await getWifiIpByIfconfig(SN);
      if (ip.length > 0 || getWithInfo) return ip;
      ip = await getWifiIpBySocket(SN);
      return ip;
    } catch (err) {
      throw new BadRequestException(err);
    }
  }
}
